﻿using System;
using System.Data;
using System.Reflection;
using System.Security.Cryptography;

namespace LxCore
{
    public class JsIdentifyList<T> : JsList<T>, IIdentityList
        where T : JsIdentifyItem
    {
        public T this[string name]
        {
            get
            {
                foreach (var item in this)
                {
                    if (item?.Name == name) { return item; }
                }
                return null;
            }
        }
        public int IndexOf(string name)
        {
            foreach (var item in this)
            {
                if (item?.Name == name) { return item.ID; }
            }
            return -1;
        }

        public override void Add(T item)
        {
            base.Add(item);
            if (item != null)
            {
                item.Name = item.Name;//触发一次名称检查
                item.ID = ListData.Count - 1;
            }
        }

        public override void Insert(int index, T item)
        {
            base.Insert(index, item);
            if (item != null)
            {
                item.Name = item.Name;//触发一次名称检查
            }
            for (int i1 = index; i1 < ListData.Count; i1++)
            {
                if (ListData[i1] != null)
                {
                    ListData[i1].ID = i1;
                }
            }
        }
        public override void RemoveAt(int index)
        {
            T old = this[index];
            base.RemoveAt(index);
            for (int i1 = index; i1 < ListData.Count; i1++)
            {
                ListData[i1].ID = i1;
            }
            if (old != null)
            {
                old.ID = -1;
            }
        }
        public override bool Remove(T item)
        {
            if (base.Remove(item))
            {
                for (int i1 = 0; i1 < ListData.Count; i1++)
                {
                    ListData[i1].ID = i1;
                }
                if (item != null)
                {
                    item.ID = -1;
                }
                return true;
            }
            else
            {
                return false;
            }
        }
        public override void Clear()
        {
            var old = ListData;
            base.Clear();
            foreach (var item in old)
            {
                item.ID = -1;
            }
        }
        public bool HasSameName(string name, JsIdentifyItem self)
        {
            foreach (T e in ListData)
            {
                if (string.Equals(name, e?.Name) && !ReferenceEquals(e, self))
                {
                    return true;
                }
            }
            return false;
        }
    }
}
